#include "SDL.h"
#include <algorithm>
#include "EventPoller.h"
#include "Log.h"
#include "Error.h"
#include "EventHandler.h"
#include "Game.h"

namespace Engine
{
	bool EventPoller::Initialize()
	{
		Log("****Initialize Event Poller****");
		if(SDL_InitSubSystem(SDL_INIT_EVENTTHREAD) == -1)
		{
			Error("Unable to initialize Event Poller");

			return false;
		}
		Log("Event Poller initialized");
		Log(" ");
		return true;
	}

	void EventPoller::Update()
	{	
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			HandlerList tempHandlerList = m_handlers;
			switch(event.type)
			{
				case SDL_KEYUP:
					//fall through
				case SDL_KEYDOWN:
				{
					for(HandlerList::iterator it = tempHandlerList.begin(); 
						it != tempHandlerList.end(); ++it)
					{
						if((*it) ->IsActive())
							(*it) ->OnKeyboardEvent(event.key);
					}

					break; 
				}

				case SDL_MOUSEMOTION:
				{
					for(HandlerList::iterator it = tempHandlerList.begin(); 
						it != tempHandlerList.end(); ++it)
					{
						if((*it) ->IsActive())
							(*it) ->OnMouseMotionEvent(event.motion);
						
					}
					break;
				}

				case SDL_MOUSEBUTTONUP:
					//fall through
				case SDL_MOUSEBUTTONDOWN:
				{
					for(HandlerList::iterator it = tempHandlerList.begin(); 
						it != tempHandlerList.end(); ++it)
					{
						if((*it) ->IsActive())
							(*it) ->OnMouseButtonEvent(event.button);
					}
					break;
				}

				case SDL_QUIT:
				{
					for(HandlerList::iterator it = tempHandlerList.begin(); 
						it != tempHandlerList.end(); ++it)
					{
						if((*it) ->IsActive())
							(*it) ->OnQuit();
					}
					break;
				}
			}
		}
	}

	void EventPoller::AddHandler(EventHandler* e)
	{
		m_handlers.push_back(e);
	}

	void EventPoller::RemoveHandler(EventHandler* e)
	{
		for(HandlerList::iterator it = m_handlers.begin(); 
			it != m_handlers.end(); ++it)
		{
			if(*it == e) 
			{
				m_handlers.erase(it);
				return;
			}
		}
	}

	void EventPoller::RemoveAllHandlers()
	{
		m_handlers.clear();
	}

	EventPoller::~EventPoller()
	{
		if(m_event)
			delete m_event;
	}
}
